﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using UnityEngine;
using Random = UnityEngine.Random;
using Debug = UnityEngine.Debug;

public class Utils  {


    public static T GetSafeComponet<T>(GameObject target) where T:Behaviour
    {
        T t = target.GetComponent<T>();
        if (t == null)
            t = target.AddComponent<T>();
        return t;
    }

    public static List<int> GetRandomNoSame(int minNum, int maxNum, int ResultCount)
    {
        List<int> numbers = new List<int>();
        List<int> finals = new List<int>();
        for (int i = minNum; i < maxNum; i++)
            numbers.Add(i);

        for (int i = 0; i < ResultCount; i++)
        {
            int index = Random.Range(0, numbers.Count);
            //Debug.Log(numbers[index]);
            finals.Add(numbers[index]);
            numbers.RemoveAt(index);
        }

        return finals;
    }

    /// <summary>
    /// 一次创建多级目录中的文件
    /// </summary>
    /// <param name="path">d:/aa/bb/c.txt</param>
    public static void CreateFileRecuIfNotExist(string path)
    {
        string dir = Path.GetDirectoryName(path);
        CreateDirRecuIfNotExist(dir);

        CreateFileIfNotExist(path);
    }

    /// <summary>
    /// 一次创建多级目录
    /// </summary>
    /// <param name="dir">d:/aa/bb</param>
    public static void CreateDirRecuIfNotExist(string dir)
    {
        try
        {
            if (dir.Contains("/"))
            {
                string[] p = dir.Split('/');

                string str = p[0];
                CreateDirIfNotExist(str);

                for (int i = 1; i < p.Length; i++)
                {
                    if (!string.IsNullOrEmpty(p[i]))
                    {
                        str += "/" + p[i];
                        CreateDirIfNotExist(str);
                    }
                }
            }
        }
        catch(Exception e) {
            Debug.LogError(e.Message);
        }
    }

    public static void CreateDirIfNotExist(string dir)
    {
        if (!Directory.Exists(dir))
            Directory.CreateDirectory(dir);
    }

    public static FileStream CreateFileIfNotExist(string path)
    {
        if (!File.Exists(path))
            return File.Create(path);

        return null;
    }

    public static void DestroyChildObjects(Transform parent,List<string> ignore_objects)
    {
        if (parent.childCount == 0) return;

        List<GameObject> childs = new List<GameObject>();
        for (int i = 0; i < parent.childCount; i++)
        {
            Transform child = parent.GetChild(i);
            if(!ignore_objects.Contains(child.name))
                childs.Add(child.gameObject);
        }

        for (int i = 0; i < childs.Count; i++)
            GameObject.Destroy(childs[i]);
    }

    public static void GetAllSubFiles(string dir,ref List<string> files)
    {
        if (Directory.Exists(dir))
        {
            string[] fs = Directory.GetFiles(dir);
            if(fs.Length > 0)
                foreach (var item in fs)
                {
                    files.Add(item);
                }

            string[] ds = Directory.GetDirectories(dir);
            if (ds.Length > 0)
            {
                foreach (var item in ds)
                {
                    files.Add(item);
                    GetAllSubFiles(item, ref files);
                }
            }
        }
        else
        {
            Debug.LogError("不存在这个目录");
        }
    }

    public static void CopyDir(string srcPath, string aimPath)
    {
        try
        {
            // 检查目标目录是否以目录分割字符结束如果不是则添加之
            if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar)
                aimPath += Path.DirectorySeparatorChar;
            // 判断目标目录是否存在如果不存在则新建之
            if (!Directory.Exists(aimPath))
                Directory.CreateDirectory(aimPath);
            // 得到源目录的文件列表，该里面是包含文件以及目录路径的一个数组
            // 如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
            // string[] fileList = Directory.GetFiles(srcPath);
            string[] fileList = Directory.GetFileSystemEntries(srcPath);
            // 遍历所有的文件和目录
            foreach (string file in fileList)
            {
                // 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
                if (Directory.Exists(file))
                    CopyDir(file, aimPath + Path.GetFileName(file));
                // 否则直接Copy文件
                else
                    File.Copy(file, aimPath + Path.GetFileName(file), true);
            }
        }
        catch
        {
            Debug.LogError("无法复制");
        }
    }

    /// <summary>
    /// 运行cmd命令
    /// 会显示命令窗口
    /// </summary>
    /// <param name="cmdExe">指定应用程序的完整路径</param>
    /// <param name="cmdStr">执行命令行参数</param>
    public static bool RunCmd(string cmdExe, string cmdStr)
    {
        bool result = false;
        try
        {
            using (Process myPro = new Process())
            {
                //指定启动进程是调用的应用程序和命令行参数
                ProcessStartInfo psi = new ProcessStartInfo(cmdExe, cmdStr);
                myPro.StartInfo = psi;
                myPro.Start();
                myPro.WaitForExit();
                result = true;
            }
        }
        catch
        {

        }
        return result;
    }

    /// <summary>
    /// 运行cmd命令
    /// 不显示命令窗口
    /// </summary>
    /// <param name="cmdExe">指定应用程序的完整路径</param>
    /// <param name="cmdStr">执行命令行参数</param>
    public static bool RunCmd2(string cmdExe, string cmdStr)
    {
        bool result = false;
        try
        {
            using (Process myPro = new Process())
            {
                myPro.StartInfo.FileName = "cmd.exe";
                myPro.StartInfo.UseShellExecute = false;
                myPro.StartInfo.RedirectStandardInput = true;
                myPro.StartInfo.RedirectStandardOutput = true;
                myPro.StartInfo.RedirectStandardError = true;
                myPro.StartInfo.CreateNoWindow = true;
                myPro.Start();
                //如果调用程序路径中有空格时，cmd命令执行失败，可以用双引号括起来 ，在这里两个引号表示一个引号（转义）
                string str = string.Format(@"""{0}"" {1} {2}", cmdExe, cmdStr, "&exit");

                myPro.StandardInput.WriteLine(str);
                myPro.StandardInput.AutoFlush = true;
                myPro.WaitForExit();

                result = true;
            }
        }
        catch
        {

        }
        return result;
    }

}

